import axios from 'axios'
import { Message } from 'element-ui';
// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_URL // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})

service.interceptors.request.use(//请求拦截器
  function (config) {
    // console.log("头部参数", config);
    if (config.url.startsWith('/client/')) {
      config.url = config.url.split('client')[1]
    } else {
      // 往header头自动添加token

      var userInfoData_ = JSON.parse(sessionStorage.getItem('userInfoData_web'))
      // console.log("客户端", userInfoData_);
      config.headers.Authorization = `Bearer ${userInfoData_ ? userInfoData_.access_token : ""}`;
      config.headers.clientid = userInfoData_ ? userInfoData_.client_id : "1b45e327bb9e739fa094eabd04b1140f"
    }

    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// response interceptor

service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
     console.log(response);
    if (response.config.url == "/application/resume/exportResume") {
      return response
    }
    
    // if the custom code is not 20000, it is judged as an error.
   
    if (res.code == 401) {
      Message.error(res.msg)
      setTimeout(() => {
        console.log("回退登录");
        // window.open("/login?id=login")
        window.location.href ="/login?id=login"
        // this.$router.push("/login?id=register")
      }, 500)
      return
    }
    if (res.code !== 200) {
      // console.log(res)
      Message.error(res.msg)
      return Promise.reject(new Error(res.msg || "error"))
    } else {
      return res
    }
  },
  (error) => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)
// 封装get方法  
service.get = function (url, params) {
  return service.request({
    method: 'get',
    url: url,
    params: params
  });
};

// 封装post方法  
service.post = function (url, data) {
  return service.request({
    method: 'post',
    url: url,
    data: data
  });
};

// 封装put方法  
service.put = function (url, data) {
  return service.request({
    method: 'put',
    url: url,
    data: data
  });
};

// 封装delete方法  
service.delete = function (url, params) {
  return service.request({
    method: 'delete',
    url: url,
    params: params
  });
};
export default service
